package com.vitaf.cash.app.ui.activity

import android.os.Handler
import android.os.Looper
import android.view.View
import androidx.activity.result.contract.ActivityResultContracts
import com.vitaf.cash.app.BuildConfig
import com.vitaf.cash.app.R
import com.vitaf.cash.app.common.VitafComActV2
import com.vitaf.cash.app.configs.GombeCreditApiPath
import com.vitaf.cash.app.configs.GombeCreditApiUrl
import com.vitaf.cash.app.configs.GombeCreditApiUrl.addCommonParams
import com.vitaf.cash.app.databinding.ActivitySettingBinding
import com.vitaf.cash.app.databinding.DataBindingHelper
import com.vitaf.cash.app.event.VitafEventPointType
import com.vitaf.cash.app.request.IHttpCallback
import com.vitaf.cash.app.ui.dialog.VitafUserDataDeleteDlog
import com.vitaf.cash.app.utils.helper.VitafConfigsHp
import com.vitaf.cash.app.utils.helper.VitafUpdateHp
import com.vitaf.cash.app.utils.shared.VitafSharedHp
import org.json.JSONObject

/**
 * VitafCash
 * @Author wwdeng
 * @CreateTime: 2024/11/27 16:16
 * @Annotation：设置
 */
class SettingActivity: VitafComActV2() {
    private var _binding: ActivitySettingBinding? = null
    private var deleteDataAfterDate = ""

    private var viewModel = DataBindingHelper.createModel()

    private var updateHelper: VitafUpdateHp? = null
    private val updateLauncher = registerForActivityResult(ActivityResultContracts.StartIntentSenderForResult()) { result ->
        if (result.resultCode == RESULT_OK) {
            //更新成功

        } else {

        }
    }

    override val pageName: String = "Setting_Page"

    override fun createVitafContentView(): View? {
        _binding = ActivitySettingBinding.inflate(layoutInflater)
        return _binding?.root
    }

    override fun initializeVitafViews() {
        _binding?.settingActivity = this
        _binding?.model = viewModel
        _binding?.lifecycleOwner = this
        setViewPaddingTopStatusBarHeight(_binding?.settingRootLayout)
    }

    override fun setupVitafEventListeners() {
    }

    override fun loadVitafData() {
        //获取版本名称
        viewModel.set("versionName",String.format(getString(R.string.setting_version), BuildConfig.VERSION_NAME))
        //是否有新版本
        val isUpdate = VitafConfigsHp.isGombeCreditUpdate()
        viewModel.set("isUpdate",isUpdate)

        //默认设置不显示
        viewModel.set("showDropButton",false)
        //需要判断是否需要显示删除用户数据按钮
        submitGombeCreditUserDataDeleteAction(true)
    }

    override fun onResume() {
        super.onResume()
        updateHelper?.resumeIfInProgress()
    }

    /**
     * 版本更新
     */
    fun onSettingClickCheckUpdate(){
        //是否有新版本
        val isUpdate = VitafConfigsHp.isGombeCreditUpdate()
        if (!isUpdate){
            showVitafToast(getString(R.string.gombe_credit_update_no_version))
            return
        }
        if (updateHelper == null){
            updateHelper = VitafUpdateHp(activity = this, forceUpdate = false, updateLauncher)
        }
        updateHelper?.checkAndStartUpdate { }
    }

    /**
     * 清空用户数据
     */
    fun onSettingClickDeleteData(){
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.USER_DATA_CLEAR)
        showUserClearDataDialog()
    }

    /**
     * 退出登录
     */
    fun onSettingClickLogOut(){
        addEventPointRequestAction(VitafEventPointType.GOMBECREDIT_TRACK_CLICK.USER_LOGINOUT)
        //退出登录，需要移除用户保存的信息
        VitafSharedHp.onGombeCreditLoginOut()
        Handler(Looper.getMainLooper()).postDelayed({
            onIntent(VitafUserLoginAct::class.java)
        },300)
    }

    /**
     * 清空用户数据dialog
     */
    private fun showUserClearDataDialog(){
        val clearDialog = VitafUserDataDeleteDlog(this,"Setting Page",object : VitafUserDataDeleteDlog.IDialogCallback{
            override fun onUserDataClearConfirmClick() {
                submitGombeCreditUserDataDeleteAction(false)
            }
        })
        clearDialog.setCancelable(true)
        clearDialog.setCanceledOnTouchOutside(true)
        clearDialog.show()
        clearDialog.showGombeCreditUserDataDeleteInfo(VitafConfigsHp.takeGombeCreditDeletePersonalDataDesc(),deleteDataAfterDate)
    }

    /**
     * 清除用户数据 或 获取是否显示删除数据按钮
     */
    private fun submitGombeCreditUserDataDeleteAction(isShowDeleteButton: Boolean){
        showVitafLoading()
        val httpUrl = GombeCreditApiUrl.takeRequestUrl()
        val params = JSONObject().addCommonParams().apply {
            put("path", GombeCreditApiPath.GOMBECREDIT_PATH.GOMBECREDIT_API_USER_DATA_CLEAR_PATH)
        }
        if (isShowDeleteButton){
            params.put("type","GET")
        } else {
            params.put("type","DROP")
        }
        doPostAction(httpUrl, params, object : IHttpCallback {
            override fun onRequestSuccess(data: JSONObject) {
                if (isShowDeleteButton){
                    val obj = data.optJSONObject("obj")
                    obj?.let {
                        viewModel.set("showDropButton",obj.optString("showDropButton") == "YES")
                    }
                } else {
                    hideVitafLoading()
                    //退出登录，需要移除用户保存的信息
                    VitafSharedHp.onGombeCreditLoginOut()
                    onIntent(VitafUserLoginAct::class.java)
                }
            }
            override fun onRequestError(error: JSONObject) {
                showVitafToast(error.optString("errorMsg"))
            }
            override fun onRequestFinish() {
                hideVitafLoading()
            }
        })
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
}